<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('EMAIL_KETOAN', 'yenphamthi@vccorp.vn');
define('EMAIL_SUPPORT', 'serving_support@vccorp.vn');
define('EMAIL_ADMIN', 'khanhnguyenquoc@vccorp.vn');

class Recharge extends Controller
{
	private $_template_f;
	private $_limit = 20;
	private $_status_permission_admin = array(0,1,2,-1);
	
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->_template_f = $this->config->item('template_f');
		$this->load->language('common', $this->_lang);
		$this->load->language('email_tpl', $this->_lang);
		if(!$this->session->userdata('uname'))
		{
			redirect(site_url('/login'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				$common_lang = $this->lang->line('common_lang');
				show_error($common_lang['access_denied']);
				die();
			}
		}
		
		//Kiem tra quyen phan nap tien
		$action = $this->uri->rsegment(2);
		if(!in_array(strtolower($action), array('repassword', 'postrepassword')))
		{
			$this->aclAdmin();
		}
		
		$this->load->model('recharge/recharge_model');
		
		$this->load->helper('breadcrumb');
		$this->load->language('recharge/recharge', $this->_lang);
	}
	
	function index()
	{
		$this->adList();
	}
	
	/*
	 * Form nap tien truc tiep
	 */
	function addMoney()
	{
		$lang = $this->lang->line('recharge');
		$uid = (int)$this->session->userdata('uid');
		$msg = trim($this->input->get('msg',true));
		
		$variable = array('uid','lang','msg');
		$data = array();
		foreach ($variable as $key)
		{
			$data[$key] = $$key;
		}
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'recharge/addmoney', $data);
		$this->_loadFooter();
	}
	
	function ajaxGetAccName()
	{
		$acctype = trim($this->input->get('acctype',true));
		$lang = $this->lang->line('recharge');
		$html = '<option value="0">'.$lang['please_select'].'</option>';
		if($acctype == 'user')
		{
			$items = $this->recharge_model->getall_user();
			foreach ($items as $a)
			{
				$html .= '<option value="'.$a->user_id.'">'.$a->username.'</option>';
			}
		}
		else if($acctype == 'agency')
		{
			$items = $this->recharge_model->getall_agency();
			foreach ($items as $a)
			{
				$html .= '<option value="'.$a->groupid.'">'.$a->groupname.'</option>';
			}
		}
		echo $html;
	}
	
	/*
	 * Nhan thong tin form yeu cau nap tien (method: post)
	 */
	function saveMoney()
	{
		if(isset($_POST['txtAmount']) && (int)$_POST['txtAmount'] > 0)
		{
			$lang = $this->lang->line('recharge');
			$uid = (int)$this->session->userdata('uid');
		
			$amount = str_replace(',','',trim($this->input->post('txtAmount',true)));
			$description = trim($this->input->post('txtDescription',true));
			$acctype = trim($this->input->post('acctype',true));
			$accname = (int)$this->input->post('accname',true);
			if(!is_numeric($amount) || (int)$amount <= 0)
			{
				redirect(site_url('recharge/addmoney/?msg='.base64_encode($lang['enter_amount'])));
				die();
			}
			if(($acctype != 'user' && $acctype != 'agency') || $accname <= 0)
			{
				redirect(site_url('recharge/addmoney/?msg='.base64_encode($lang['enter_user'])));
				die();
			}
			
			//Nap tien
			$this->recharge_model->add_money($accname, $uid, (int)$amount, $description, ($acctype == 'agency' ? 1 : 0));
			
			//Gui mail cho support
			$for_username = '';
			if($acctype == 'user')
			{
				$for_username = $this->recharge_model->get_user_info($accname);
				$for_username = $lang['user'].' '.$for_username['username'];
			}
			else
			{
				$for_username = $this->recharge_model->get_user_group_info($accname);
				$for_username = $lang['agency'].' '.$for_username->groupname;
			}
			$email = array();
			$email['to'] = EMAIL_SUPPORT;
			$email['subject'] = $lang['email_subject_3'];
			$email['body'] = $lang['email_content_6'];
			$email['body'] = str_replace('[amount]',number_format($amount),$email['body']);
			$email['body'] = str_replace('[for_user]',$for_username,$email['body']);
			$this->mycommon->sendmail($email);
			$this->recharge_model->email_log_insert($this->config->item('serving_email'),$email['to'],'',$email['subject'],$email['body'],0,$uid);
			
			redirect(site_url('recharge/addmoney/?msg='.base64_encode($lang['add_money_success']))); die();
		}
		
		redirect(site_url('recharge')); die();
	}
	
	/*
	 * List cac yeu cau cho ke toan
	 */
	function adList()
	{
		$lang = $this->lang->line('recharge');
		$uid = (int)$this->session->userdata('uid');
		$permit = (int)$this->session->userdata('permitid');
		$group = (int)$this->session->userdata('groupid');
		$data = array();
		$arr_permiss = $this->_status_permission_admin;
		$status = trim($this->input->get('status',true));
		if($status == '') $status = 1;
		else $status = (int)$status;
		if(!in_array($status, $arr_permiss)) $status = 1;	//Admin chi duoc view 3 trang thai cho phep
		$page = (int)$this->input->get('page', true);
		if($page < 1) $page = 1;
		$fromdate = $this->input->get('fromdate');
		$fromdate = ($fromdate == '') ? date('Y-m-d', strtotime ( '-7 day' , strtotime (date('Y-m-d')))) : $fromdate;
		$todate = $this->input->get('todate');
		$todate = ($todate == '') ? date('Y-m-d') : $todate;
		$typead = (int)$this->input->get('typead',true);
		if($typead == 0)
		{
			$typead = 1;
		}
		$sch_userid = $this->input->get('userid');
		if($sch_userid == '')
		{
			$sch_userid = -1;
			$data['sch_username'] = '';
			$data['sch_userid'] = '';
		}
		else
		{
			$infouser = $this->recharge_model->get_user_info($sch_userid);
			$data['sch_username'] = $infouser['username'];
			$data['sch_userid'] = $sch_userid;
		}
		$stt = 0;
		$items = $this->recharge_model->recharge_getall($status, $fromdate, $todate, '', $page, $this->_limit, $typead, $sch_userid);
		$pages = $items['pages'];
		$items = $items['items'];
		
		$variable = array('uid','permit','group','lang','items','pages','page','stt','status','fromdate','todate','arr_permiss','typead');
		
		foreach ($variable as $key)
		{
			$data[$key] = $$key;
		}
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'recharge/adlist', $data);
		$this->_loadFooter();
	}
	
	/*
	 * Cap nhat trang thai cua admin
	 */
	function adUpdateStatus()
	{
		$lang = $this->lang->line('recharge');
		$uid = (int)$this->session->userdata('uid');
		
		$id = (int)$this->input->post('id',true);
		$status = (int)$this->input->post('status',true);
		$des = trim($this->input->post('des', true));
		$date = trim($this->input->post('date', true));
		
		$recharge = $this->recharge_model->get_recharge_info($id);
		//if(!in_array($status, $this->_status_permission_admin) || $recharge == null)
		if($recharge == null)
		{
			echo $lang['not_permission_update_status'];
			die();
		}
		if($recharge->status != 1 && $status == 2)
		{
			echo $lang['permit_status_not_change'];
			die();
		}

		//Update status
		$this->recharge_model->updateStatusRecharge($id, $status, $uid, $recharge->real_money, $des);
		if($status == 2)	//Admin thuc hien nap tien
		{
			if($recharge->typead == 1) $this->recharge_model->add_money($recharge->for_uid, $recharge->typeuser, $recharge->real_money, $recharge->content, $recharge->typepay, $recharge->receipts, $date, $uid);
			else $this->recharge_model->add_money_cpm4k($recharge->for_uid, $recharge->typeuser, $recharge->real_money, $recharge->content, $recharge->typepay, $recharge->receipts, $date, $uid);
			$send = $this->config->item('serving_email');
			//Gui email cho nguoi yeu cau
			$email_lang = $this->lang->line('email_tpl_lang');
			$email = array();
			$email['langcode'] = $this->_lang;
			$email['link'] = array(
				'imagepath' => str_replace('/admin', '', base_url().'images/email/'),
				'home'=> str_replace('/admin/', '', base_url()),
				'login' => str_replace('/admin', '', site_url('login'))
			);
			$email['common_lang'] = $email_lang['common'];
			$email['create'] = false;
			
			$email['to'] = $recharge->crateemail;
			$email['cc'] = $recharge->recieveemail.','.EMAIL_KETOAN.','.EMAIL_SUPPORT;
			$email['subject'] = $lang['email_subject_3'];
			$email['body'] = $lang['email_content_4'];
			$email['body'] = str_replace('[username]',$recharge->createname,$email['body']);
			$email['body'] = str_replace('[amount]',number_format($recharge->real_money),$email['body']);
			$email['body'] = str_replace('[for_user]',$recharge->recievename,$email['body']);
			$email['email_lang'] = $email_lang;
			$template = $this->load->view($this->_template_f . 'emailtpl/email_recharge_alert_view', $email, true);
			$email['body'] = $template;
			$this->mycommon->sendmail($email);
			$this->recharge_model->email_log_insert($send,$email['to'],'',$email['subject'],$this->mycommon->getSaveSqlStr($email['body']),$id,$uid);
		}
		elseif($status == -1)	//Admin huy yeu cau
		{
			$send = $this->config->item('serving_email');
			//Gui email cho nguoi yeu cau
			$email_lang = $this->lang->line('email_tpl_lang');
			$email = array();
			$email['langcode'] = $this->_lang;
			$email['link'] = array(
				'imagepath' => str_replace('/admin', '', base_url().'images/email/'),
				'home'=> str_replace('/admin/', '', base_url()),
				'login' => str_replace('/admin', '', site_url('login'))
			);
			$email['common_lang'] = $email_lang['common'];
			$email['create'] = false;
			
			$email['to'] = $recharge->crateemail;
			$email['cc'] = $recharge->recieveemail.','.EMAIL_KETOAN;
			$email['subject'] = $lang['email_subject_1'];
			$email['body'] = $lang['email_content_7'];
			$email['body'] = str_replace('[username]',$recharge->createname, $email['body']);
			$email['body'] = str_replace('[amount]',number_format($recharge->real_money), $email['body']);
			$email['body'] = str_replace('[for_user]',$recharge->recievename, $email['body']);
			$email['body'] = str_replace('[mess]',$des, $email['body']);
			$email['email_lang'] = $email_lang;
			$template = $this->load->view($this->_template_f . 'emailtpl/email_recharge_alert_view', $email, true);
			$email['body'] = $template;
			$this->mycommon->sendmail($email);
			$this->recharge_model->email_log_insert($send,$email['to'],'',$email['subject'],$this->mycommon->getSaveSqlStr($email['body']),$id,$uid);
		}
		echo 1;
	}
	
	function adDetail()
	{
		$id = (int)$this->input->get('id', true);
		$typead = (int)$this->input->get('typead', true);
		if($typead == 0) $typead = 1;
		$row = $this->recharge_model->get_recharge_info($id);
		if($row == null || !isset($row->id) || (int)$row->id <= 0)
		{
			redirect(site_url('recharge')); die();
		}
		
		$data = array();
		$data['row'] = $row;
		$data['lang'] = $this->lang->line('recharge');
		$data['typead'] = $typead;
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'recharge/detail', $data);
		$this->_loadFooter();
	}
	
	function create()
	{
		$uid = (int)$this->session->userdata('uid');
		$uid = $this->recharge_model->get_user_info($uid);
		$msg = trim($this->input->get('msg',true));
		$groups = $this->recharge_model->get_user_group_listall();
		
		$data = array();
		$data['lang'] = $this->lang->line('recharge');
		$data['msg'] = $msg;
		$data['uid'] = $uid;
		$data['groups'] = $groups;
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'recharge/create', $data);
		$this->_loadFooter();
	}
	
	function createSave()
	{
		if(isset($_POST['txtAmount']) && (int)$_POST['txtAmount'] > 0)
		{
			$lang = $this->lang->line('recharge');
			$uid = (int)$this->session->userdata('uid');

			$amount = str_replace(',','',trim($this->input->post('txtAmount',true)));
			$content = trim($this->input->post('txtDescription',true));
			$receipts = trim($this->input->post('txtReceipts',true));
			$typePay = (int)$this->input->post('txtTypePay',true);
			$des = trim($this->input->post('txtDes',true));
			$system = (int)$this->input->post('txtSystem',true);
			$for_uid = 0;
			$typeUser = (int)$this->input->post('txtTypeUser',true);
			if($typeUser == 1)	//cho dai ly
			{
				$for_uid = (int)$this->input->post('txtForGroup',true);
			}
			else	//cho user truc tiep
			{
				$user  = trim($this->input->post('txtForUser',true));
				$user = $this->recharge_model->get_user_info_by_uname($user);
				if(isset($user->user_id) && (int)$user->user_id > 0)
				{
					$for_uid = (int)$user->user_id;
				}
				else
				{
					redirect(site_url('recharge/create/?msg='.base64_encode($lang['enter_user'])));
					return false;
				}
			}
			
			if(!is_numeric($amount) || $amount <= 0)
			{
				redirect(site_url('recharge/create/?msg='.base64_encode($lang['enter_amount'])));
				return false;
			}
			if($receipts == '')
			{
				redirect(site_url('recharge/create/?msg='.base64_encode($lang['enter_receipts'])));
				return false;
			}

			if(!in_array($typeUser, array(0, 1)) || $for_uid <= 0)
			{
				redirect(site_url('recharge/create/?msg='.base64_encode($lang['enter_user'])));
				return false;
			}
			
			if($typePay == 0)
			{
				redirect(site_url('recharge/create/?msg='.base64_encode($lang['enter_type_pay'])));
				return false;
			}
			else if($typePay == 1) $typePay = $lang['add_money'];
			else $typePay = $lang['transfer_money'];
			
			//Luu yeu cau
			$rechargeId = $this->recharge_model->insert_request_recharge($uid, $for_uid, $typeUser, $amount, $content, $typePay, $receipts, $des, $system, 1);
			$send = $this->config->item('serving_email');
			
			//Gui mail cho nguoi nop tien va ke toan
			$recharge = $this->recharge_model->get_recharge_info($rechargeId);
			if($recharge != null && isset($recharge->id) && $recharge->id > 0)
			{
				//Gui email cho nguoi yeu cau
				$email_lang = $this->lang->line('email_tpl_lang');
				$email = array();
				$email['langcode'] = $this->_lang;
				$email['link'] = array(
					'imagepath' => str_replace('/admin', '', base_url().'images/email/'),
					'home'=> str_replace('/admin/', '', base_url()),
					'login' => str_replace('/admin', '', site_url('login'))
				);
				$email['common_lang'] = $email_lang['common'];
				$email['create'] = true;
				if($typeUser == 0)
				{
					$email['to'] = $recharge->crateemail;
					$email['cc'] = EMAIL_KETOAN.','.$recharge->recieveemail;
				}
				else
				{
					$email['to'] = $recharge->crateemail;
					$email['cc'] = EMAIL_KETOAN;
				}
				$email['subject'] = $lang['email_subject_1'];
				$email['body'] = $lang['email_content_1'];
				$email['body'] = str_replace('[username]',$recharge->createname,$email['body']);
				$email['body'] = str_replace('[amount]',number_format($amount),$email['body']);
				$email['body'] = str_replace('[for_user]',$recharge->recievename,$email['body']);
				$email['email_lang'] = $email_lang;
				$template = $this->load->view($this->_template_f . 'emailtpl/email_recharge_alert_view', $email, true);
				$email['body'] = $template;
				$this->mycommon->sendmail($email);
				$this->recharge_model->email_log_insert($send,$email['to'],'',$email['subject'],$this->mycommon->getSaveSqlStr($email['body']),$rechargeId,$uid);
			}
			redirect(site_url('recharge/create/?msg='.base64_encode($lang['request_success'])));
			return true;
		}
		
		redirect(site_url('recharge'));
		return false;
	}
	
	function ajaxCheckUsername()
	{
		$user = trim($this->input->get('uname',true));
		$user = $this->recharge_model->get_user_info_by_uname($user);
		if(isset($user->user_id) && (int)$user->user_id > 0) echo 1;
		else echo 0;
	}
	
	function rePassword()
	{
		$data = array();
		$data['lang'] = $this->lang->line('recharge');
		$data['msg'] = trim($this->input->get('msg',true));
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'recharge/repassword', $data);
		$this->_loadFooter();
	}
	
	function postRePassword()
	{
		$username = $this->session->userdata('uname');
		$password = trim($this->input->post('txtPassword', true));
		$lang = $this->lang->line('recharge');
		if($password == '')
		{
			redirect(site_url('recharge/repassword/?msg='.base64_encode($lang['password_false'])));
			die();
		}
		//kiem tra login
		$item = $this->recharge_model->checkLogin($username, md5($password));
		if($item == null || (int)$item->user_id <= 0)
		{
			redirect(site_url('recharge/repassword/?msg='.base64_encode($lang['password_false'])));
			die();
		}
		else
		{
			$this->session->set_userdata('repass', true);
			redirect(site_url('recharge')); die();
		}
	}
	
	function aclAdmin()
	{
		$username = $this->session->userdata('uname');
		if(!in_array($username, array('ali', 'ngocnd', 'tuanha')))
		{
			redirect(site_url('')); die();
		}
		if(!$this->session->userdata('repass'))
		{
			redirect(site_url('recharge/repassword')); die();
		}
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
		$header['lang'] = $this->_lang;
		$header['module_name'] = 'home';
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		
		// load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
	
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
		
		$this->load->view($this->_template_f . 'menu_view', $data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}

}